package com.jfinal.demo.web.controller;

import java.io.File;
import java.util.List;

import com.jfinal.aop.Before;
import com.jfinal.core.Controller;
import com.jfinal.demo.config.common.Constants;
import com.jfinal.demo.core.entity.Member;
import com.jfinal.demo.core.service.MemberService;
import com.jfinal.demo.web.validator.MemberValidator;
import com.jfinal.plugin.ehcache.CacheInterceptor;
import com.jfinal.plugin.ehcache.CacheName;
import com.jfinal.plugin.ehcache.EvictInterceptor;
import com.jfinal.upload.UploadFile;

/**
 * 会员 controller
 * 
 * @author Administrator
 * 
 */
public class MemberController extends Controller {

	public static final String MEMBER_FILE_PREFIX = "member";

	private MemberService memberService = MemberService.memberService;

	public void show() {
		Integer id = getParaToInt("id");
		Member member = null;
		if (id != null) {
			member = memberService.findMemberById(id);
		}

		setAttr("member", member).render("show.jsp");
	}

	@Before({ MemberValidator.class, EvictInterceptor.class })
	@CacheName(Constants.MEMBER_CACHE_NAME)
	public void saveOrUpdate() {
		UploadFile file = getFile("file", MEMBER_FILE_PREFIX);

		Member member = getModel(Member.class, "member");
		if (file != null) {
			String fileName = MEMBER_FILE_PREFIX + File.separator
					+ file.getFileName();
			member.set("filePath", fileName);
		} else {
			member.set("filePath", null);
		}
		memberService.saveOrUpdateMember(member);

		redirect("/member/list");
	}

	@Before({ CacheInterceptor.class })
	@CacheName(Constants.MEMBER_CACHE_NAME)
	public void list() {
		List<Member> list = memberService.findAllMembers();
		setAttr("list", list).render("list.jsp");
	}

	@Before({ EvictInterceptor.class })
	@CacheName(Constants.MEMBER_CACHE_NAME)
	public void delete() {
		Integer id = getParaToInt("id");
		memberService.deleteMemberById(id);
		redirect("/member/list");
	}
}
